import { createServer as http } from 'http';
import { createServer as https } from 'https';
import { configs } from '../src/config';
import { CustomServer, NextApp } from './app';
import { AuthConf } from './middleware/auth';
import { UserRole, UserSessionInfo } from './model/user';
import { createSessionUser } from './util/asyncUtils';
import setupLogger from './util/logger';

const dev = process.env.NODE_ENV !== 'production';
const local = process.env.APP_ENV === 'localhost';
/**
 * This is a helper function for Developement purpose only.
 * Authentication process will be skipped and this fake user be active.
 */
const createFakeUser = async (): Promise<UserSessionInfo> => {
  return await createSessionUser({
    email: 'guest@samsung.com',
    loginid: 'guest',
    username: 'Samsung Kim',
    ugroup: 'System R&D Group',
    role: UserRole.Customer,
  });
};

// launch server
(async () => {
  try {
    setupLogger();
    await NextApp.prepare();
    const server = CustomServer('webfront', !local, !local);
    // listen on all interfaces...
    http(server).listen(configs.serverPort, '0.0.0.0', (err?: any) => {
      if (err) throw err;
      console.info(`webfront > Ready on :${configs.serverPort}`);
    });
    if (dev) {
      // DEV-ONLY
      const test = CustomServer('auth-test', true, true);
      https(AuthConf.httpsOptions, test).listen(AuthConf.port, '0.0.0.0', (err?: any) => {
        if (err) throw err;
        console.info(`auth-test > Ready on :${AuthConf.port}`);
      });
    }
  } catch (e) {
    console.error(e);
    process.exit(1);
  }
})();
